<template>
  <div id="addColumn" class="container">
    <div>
      <h3 class="title"><span />添加栏目</h3>
      <el-button size="small" icon="el-icon-arrow-left" type="primary" class="back" @click="prev">返回</el-button>
    </div>
    <el-form ref="addForm" :model="addForm" :rules="columnRules" inline label-width="150px" class="addForm">
      <div class="left">
        <h5 class="title"><span /> 基本信息</h5>
        <el-form-item label="类型:" prop="type">
          <el-radio-group v-model="addForm.type" @change="raidoChange">
            <el-radio :label="1">列表栏目</el-radio>
            <el-radio :label="2">频道封面</el-radio>
            <el-radio :label="3">跳转链接</el-radio>
            <el-radio :label="4">单页面</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="栏目名称:" prop="title">
          <el-input v-model="addForm.title" />
        </el-form-item>
        <el-form-item v-if="addForm.type !=2" :label="addForm.type==3?'访问地址':'栏目别名:'" prop="alias">
          <el-input
            v-model="addForm.alias"
            :placeholder="addForm.type ==3?'访问地址以http://或者https://开头':'别名由英文字母数字和 - _ / 组成并以 / 开头' "
          />
        </el-form-item>
        <div v-if="addForm.type == 1 || addForm.type == 4">
          <el-form-item v-if="addForm.type == 1" label="模型:" :prop="addForm.type == 1?'module_id':''">
            <el-select v-model="addForm.module_id">
              <el-option
                v-for="item in moduleList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="列表页模板:" prop="list_tpl">
            <el-select v-model="addForm.list_tpl">
              <el-option
                v-for="item in tempList"
                :key="item.id"
                :label="item.file"
                :value="item.file"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="addForm.type == 1" label="详情页模板:" prop="detail_tpl">
            <el-select v-model="addForm.detail_tpl">
              <el-option
                v-for="item in tempList"
                :key="item.id"
                :label="item.file"
                :value="item.file"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="排序:">
          <el-input v-model="addForm.sort" />
        </el-form-item>
        <el-form-item label="简介:">
          <el-input v-model="addForm.desc" />
        </el-form-item>
        <el-form-item label="描述:">
          <el-input v-model="addForm.description" type="textarea" :autosize="{ minRows: 4, maxRows: 8}" />
        </el-form-item>

        <el-form-item size="small" label="缩略图:">
          <div class="attachmentBtn">
            <el-upload
              :headers="myHeaders"
              class="avatar-uploader"
              :action="$store.getters.updateURL+'/attachment/uploadAndSave'"
              :show-file-list="false"
              :on-success="uploadImg"
              :before-upload="beforeAvatarUpload"
              :data="{type:2}"
            >
              <!-- <img v-if="addForm.thumbnail" :src="imageUrl" class="avatar">
          <img v-else class="avatar" :src="require('../../images/icon1.png')" alt="">
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过1MB
          </div>
          <div style="font-size: 12px;color: #999999;line-height: 30px;font-weight: 500" /> -->
              <el-button size="small" type="primary" icon="el-icon-upload2">点击上传</el-button>
            </el-upload>
            <el-button
              size="small"
              class="blue"
              type="primary"
              icon="el-icon-s-unfold"
              @click="openList('thumbnail')"
            >选择附件</el-button>
          </div>
          <div class="imgBox">
            <img v-if="addForm.thumbnail" :src="thumbnail" class="attachmentImg">
          </div>
          <BouncedDialog title="选择附件" :dialog-show.sync="dialogShow" :width="70" class="attachment">
            <el-table
              v-el-table-infinite-scroll="load"
              :data="attachmentData"
              border
              :header-cell-style="{'text-align':'center','background-color':'#fff'}"
              :cell-style="{'text-align':'center'}"
            >
              <el-table-column label="ID" prop="id" width="60px" />
              <el-table-column label="预览">
                <template slot-scope="scope">
                  <el-image
                    :src="scope.row.url"
                    alt=""
                    class="attachmentImg"
                    :preview-src-list="scope.row.imagelist"
                  />
                </template>
              </el-table-column>
              <el-table-column label="文件名" prop="name" />
              <el-table-column label="文件大小" prop="size" width="100px" />
              <el-table-column label="Mime类型" prop="mime_type" width="100px" />
              <el-table-column label="创建日期" prop="create_time" width="160px" />
              <el-table-column label="操作" width="120px">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-check" @click="choose(scope.row)">选择</el-button>
                </template>
              </el-table-column>
            </el-table>
          </BouncedDialog>
        </el-form-item>
        <el-form-item size="small" label="banner图:">
          <div class="attachmentBtn">
            <el-upload
              :headers="myHeaders"
              class="avatar-uploader"
              :action="$store.getters.updateURL+'/attachment/uploadAndSave'"
              :show-file-list="false"
              :on-success="uploadbannerImg"
              :before-upload="beforeAvatarUpload"
              :data="{type:2}"
            >
              <!-- <img v-if="addForm.thumbnail" :src="imageUrl" class="avatar">
          <img v-else class="avatar" :src="require('../../images/icon1.png')" alt="">
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过1MB
          </div>
          <div style="font-size: 12px;color: #999999;line-height: 30px;font-weight: 500" /> -->
              <el-button size="small" type="primary" icon="el-icon-upload2">点击上传</el-button>
            </el-upload>
            <el-button
              size="small"
              class="blue"
              type="primary"
              icon="el-icon-s-unfold"
              @click="openList('banner')"
            >选择附件</el-button>
          </div>
          <div class="imgBox">
            <img v-if="addForm.banner" :src="banner" class="attachmentImg">
          </div>
        </el-form-item>
      </div>
      <div class="right">
        <h5 class="title"><span /> SEO设置</h5>
        <el-form-item label="Title:">
          <el-input v-model="addForm.seo_title" />
        </el-form-item>
        <el-form-item label="Keyword:">
          <el-input v-model="addForm.seo_keywords" />
        </el-form-item>
        <el-form-item label="Description:">
          <el-input v-model="addForm.seo_description" type="textarea" />
        </el-form-item>
        <div class="btn">
          <el-button type="primary" class="save" size="small" @click="submit()">添加</el-button>
          <el-button size="small" class="exit" @click="prev">返 回</el-button>
        </div>
      </div>

    </el-form>

  </div>
</template>

<script>
import columnApi from '@/api/column'
import moduleApi from '@/api/module'
import tempApi from '@/api/theme'
import attachmentApi from '@/api/system/attachment'
import { getToken } from '@/utils/auth'
var token = 'Bearer ' + getToken()
export default {
  data() {
    return {
      attachmentLimit: 10,
      dialogShow: false,
      attachmentData: [],
      imagelist: [],
      imagetype: '',
      myHeaders: { Authorization: token },
      headers: {},
      thumbnail: '',
      banner: '',
      imgUrl: this.$store.getters.updateURL,
      parent_id: '',
      website_id: '',
      moduleList: [],
      tempList: [],
      addForm: {
        type: 1,
        title: '',
        parent_id: '',
        website_id: '',
        alias: '',
        module_id: '',
        list_tpl: '',
        detail_tpl: '',
        description: '',
        desc: '',
        seo_description: '',
        seo_keywords: '',
        seo_title: '',
        thumbnail: '',
        lang: '',
        banner: '',
        sort: 100
      },
      lang: '',
      columnRules: {
        type: [
          { required: 'true', message: '请选择类型', trigger: 'change' }
        ],
        title: [
          { required: 'true', message: '请输入栏目名称', trigger: 'blur' }
        ],
        alias: [
          { required: 'true', message: '请输入栏目别名/访问地址', trigger: 'blur' }
        ],
        module_id: [
          { required: 'true', message: '请选择模型', trigger: 'change' }
        ],
        list_tpl: [
          { required: 'true', message: '请选择列表页模板', trigger: 'change' }
        ],
        detail_tpl: [
          { required: 'true', message: '请选择详情页模板', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    siteId1() {
      return this.$store.getters.siteId
    }
  },
  watch: {
    siteId1(val, value) {
      this.website_id = val

      if (value) {
        this.$router.push({ name: 'Category' })
      }
      this.getMould()
      this.getTemp()
    }
  },
  created() {
    this.parent_id = this.$route.query.pid
    this.website_id = this.$route.query.website_id
    this.lang = this.$route.query.lang

    // this.getColumnInfo()
    this.getMould()
    this.getTemp()
  },
  methods: {
    load() {
      this.attachmentLimit += 10
      this.getAttachmentList()
    },
    // 打开附件弹窗
    openList(val) {
      this.imagetype = val
      this.dialogShow = true
      this.getAttachmentList(val)
    },
    // 附件列表
    getAttachmentList() {
      const val = {
        limit: this.attachmentLimit,
        page: 1,
        type: 2
      }
      attachmentApi.attachmentList(val).then(res => {
        if (res.code == 0) {
          this.attachmentData = res.data
          this.imagelist = []
          // 获取每张图片的地址
          for (var x = 0;x < this.attachmentData.length;x++) {
            this.imagelist.push(this.attachmentData[x].url)
          }
          // 根据图片顺序（index）更改每张图片绑定的list的图片顺序
          for (var i = 0;i < this.attachmentData.length;i++) {
            var container = this.imagelist
            var frontArr = container.slice(0, i)
            var begindArr = container.slice(i, this.attachmentData.length)
            var list = begindArr.concat(frontArr)
            this.attachmentData[i].list = list
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 选择附件
    choose(row) {
      if (this.imagetype == 'thumbnail') {
        this.addForm.thumbnail = row.id
        this.thumbnail = row.url
      } else if (this.imagetype == 'banner') {
        this.addForm.banner = row.id
        this.banner = row.url
      }
      this.dialogShow = false
    },
    //   模型列表
    getMould() {
      moduleApi.moduleList().then(res => {
        this.moduleList = res.data
      })
    },
    // 站点下的模板
    getTemp() {
      tempApi.webTempList({ website_id: this.website_id, lang: this.lang }).then(res => {
        this.tempList = res.data
      })
    },
    // 上传banner图成功
    uploadbannerImg(res, file, fileList) {
      if (res.code == -200 || res.code == 0) {
        this.addForm.banner = res.data.id
        this.banner = res.data.url

        this.$forceUpdate()
      }
    },
    // 上传缩略图成功
    uploadImg(res, file, fileList) {
      if (res.code == -200 || res.code == 0) {
        this.addForm.thumbnail = res.data.id
        this.thumbnail = res.data.url

        this.$forceUpdate()
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },
    // getColumnInfo() {
    //   const val = {
    //     website_id: this.website_id,
    //     id: this.id
    //   }
    //
    //   columnApi.columnInfo(val).then(res => {
    //     const item = res.data
    //     this.addForm = {
    //       id: item.id,
    //       parent_id: item.parent_id,
    //       title: item.title,
    //       website_id: item.website_id,
    //       alias: item.alias,
    //       module_id: item.module_id,
    //       list_tpl: item.list_tpl,
    //       type: item.type,
    //       detail_tpl: item.detail_tpl
    //     }
    //   })
    // },
    // 切换单选按钮
    raidoChange(val) {
      if (val == 1) {
        this.addForm = {
          type: val,
          title: '',
          parent_id: '',
          website_id: '',
          alias: '',
          module_id: '',
          list_tpl: '',
          detail_tpl: '',
          description: '',
          seo_description: '',
          seo_keywords: '',
          seo_title: '',
          thumbnail: '',
          lang: '',
          banner: '',
          sort: 100
        }
      } else if (val == 2) {
        this.addForm = {
          type: val,
          title: '',
          parent_id: '',
          website_id: '',
          description: '',
          seo_description: '',
          seo_keywords: '',
          seo_title: '',
          thumbnail: '',
          lang: '',
          banner: '',
          sort: 100
        }
      } else if (val == 3) {
        this.addForm = {
          type: val,
          title: '',
          parent_id: '',
          website_id: '',
          alias: '',
          description: '',
          seo_description: '',
          seo_keywords: '',
          seo_title: '',
          thumbnail: '',
          lang: '',
          banner: '',
          sort: 100
        }
      } else if (val == 4) {
        this.addForm = {
          type: val,
          title: '',
          parent_id: '',
          website_id: '',
          alias: '',
          list_tpl: '',
          description: '',
          seo_description: '',
          seo_keywords: '',
          seo_title: '',
          thumbnail: '',
          lang: '',
          banner: '',
          sort: 100
        }
      }
    },
    // 提交
    submit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          const val = {
            title: this.addForm.title,
            parent_id: this.parent_id,
            website_id: this.website_id,
            alias: this.addForm.alias,
            module_id: this.addForm.module_id,
            list_tpl: this.addForm.list_tpl,
            type: this.addForm.type,
            detail_tpl: this.addForm.detail_tpl,
            description: this.addForm.description,
            desc: this.desc,
            seo_description: this.addForm.seo_description,
            seo_keywords: this.addForm.seo_keywords,
            seo_title: this.addForm.seo_title,
            thumbnail: this.addForm.thumbnail,
            lang: this.lang,
            banner: this.addForm.banner,
            sort: this.addForm.sort
          }

          columnApi.columnSave(val).then(res => {
            if (res.code == 0) {
              this.$message.success(res.msg)
              this.dialogShow = false
              this.$router.go(-1)
            } else {
              this.$message.error(res.msg)
            }
          })
        } else {
          this.$message.error('请填写必要信息')
        }
      })
    },
    prev() {
      this.$router.push({ name: 'Category' })
    }
  }
}
</script>
<style lang='scss'>
#addColumn{
    .el-form-item{
        width: 100%;
        .el-form-item__content{
            width: calc(100% - 150px);
            .el-select{
                width: 100%;
            }
        }
    }
}
</style>
<style scoped lang='scss'>
.addForm{
    background-color: #fff;
    padding: 50px 20px 20px;

    display: flex;
    justify-content: space-between;
    .left{
      width: 50%;
    }
    .right{
      width: 48%;
    }
    h5.title{
      height: 40px;
      line-height: 40px;
      border-left: solid 4px #f84311;
      background-color: #f5f5f5;
      font-size: 15px;
      color: #555;
      padding-left: 20px;
      margin-bottom: 20px;
    }
    .avatar{
        width: 100px;
    }
}
#app .el-form .btn{
    text-align: left;
    margin-left: 150px;

}
.back{
  position: absolute;
  right: 36px;
  top: 28px;
}
</style>
